/*
 * Copyright (c) 2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.libermundi.theorcs.comet.tapestry.services;

import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.model.MutableComponentModel;
import org.apache.tapestry5.plastic.MethodAdvice;
import org.apache.tapestry5.plastic.MethodInvocation;
import org.apache.tapestry5.plastic.PlasticClass;
import org.apache.tapestry5.plastic.PlasticMethod;
import org.apache.tapestry5.services.TransformConstants;
import org.apache.tapestry5.services.javascript.JavaScriptSupport;
import org.apache.tapestry5.services.transform.ComponentClassTransformWorker2;
import org.apache.tapestry5.services.transform.TransformationSupport;
import org.libermundi.theorcs.comet.CometConstants;
import org.libermundi.theorcs.comet.tapestry.ImportCometJS;

public class ImportCometJSWorker implements ComponentClassTransformWorker2 {
    private final JavaScriptSupport _javaScriptSupport;	
    
    public ImportCometJSWorker(
            JavaScriptSupport javaScriptSupport
            ) {
        this._javaScriptSupport = javaScriptSupport;
    }    

	@Override
	public void transform(PlasticClass plasticClass, TransformationSupport support, MutableComponentModel model) {
		
		final ImportCometJS annotation = plasticClass.getAnnotation(ImportCometJS.class);
		PlasticMethod setupRender = plasticClass.introduceMethod(TransformConstants.SETUP_RENDER_DESCRIPTION);
		
		if(annotation != null && model.isPage()) {
			setupRender.addAdvice(new MethodAdvice() {
				@Override
				public void advise(MethodInvocation invocation) {
					
					_javaScriptSupport.importStack(CometConstants.COMET_JSSTACK);
					
					invocation.proceed();
					
				}
			});
		}

		model.addRenderPhase(SetupRender.class);
	}

}
